package cn.tedu.micro.demo.emqx.mqtt;

import cn.tedu.micro.demo.emqx.serializer.MessageSerializer;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 做消息生产发送的mqtt客户端封装
 */
@Component
@Slf4j
public class MqttProducer<T>{
    @Autowired
    private MqttClient mqttClient;
    @Autowired
    private MessageSerializer messageSerializer;

    /**
     * string topic
     * int qos
     * T msg
     * boolean retained
     */
    public void send(String topic,T msg,int qos,boolean retained){
        //1.序列化处理msg
        byte[] paylaod = messageSerializer.serialize(msg);
        //2.publish
        try{
            //调用底层
            mqttClient.publish(topic,paylaod,qos,retained);
        }catch (Exception e){
            log.error("发送失败",e);
        }
    }
    //send重载,调用的业务 不需要再关心qos=1 retained=true
    public void send(String topic,T msg){
        this.send(topic,msg,1,true);
    }

}
